package com.yonyou.marketing.app.api.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.marketing.common.constants.ExceptionMessage;
import org.marketing.common.dto.customerInfo.CounselorDto;
import org.marketing.common.dto.maintain.MaintainDealerDto;
import org.marketing.common.dto.maintain.MaintainDto;
import org.marketing.common.dto.maintain.MaintainFrecordDto;
import org.marketing.common.exception.ServiceBizException;
import org.marketing.common.util.CheckUtil;
import org.marketing.common.util.DateUtil;
import org.marketing.common.util.MapConverUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yonyou.marketing.app.api.constant.AppConstant;
import com.yonyou.marketing.app.api.dao.TmCarOwnerMapper;
import com.yonyou.marketing.app.api.dao.TmDealerMapper;
import com.yonyou.marketing.app.api.dto.AppMaintainDto;
import com.yonyou.marketing.app.api.model.TmCarOwner;

@Service("appMaintainService")
public class AppMaintainService {
	private static final Logger logger = Logger.getLogger(AppMaintainService.class);
	@Autowired
	private TmDealerMapper tmDealerMapper;
	@Autowired
	private TmCarOwnerMapper tmCarOwnerMapper;
	@Autowired
	private MaintainServiceInterface maintainServiceInterface;
	@Autowired
	private CustomerServiceInterface customerServiceInterface;

	private final String city = "90011002";
	private final Long cancle = 10011005L;

	/**
	 * 养修预约选择经销商
	 * 
	 * @author Administrator
	 * @param tmTpOrderInfoMapper 
	 * @date 2017年11月15日
	 * @return
	 */
	public Map<String, Object> selectDealer(Map<String,String> pa,Integer userId) {
		TmCarOwner co = tmCarOwnerMapper.selectByPrimaryKey(userId);
		if(!CheckUtil.NullOrEmpty(pa.get("gz"))){
			pa.put("dealerCode", co.getGzDealerCode());
		}
		if("0.000000".equals(pa.get("lng"))){
			pa.put("lng", "");
		}
		if("0.000000".equals(pa.get("lng"))){
			pa.put("lng", "");
		}
		List<Map<String, Object>> result = tmDealerMapper.selectDealer(pa);
		//标记关注店
		if(!CheckUtil.NullOrEmpty(result)){
			for (Map<String, Object> map : result) {
				String dealerCode = map.get("DEALER_CODE").toString();
				if(!CheckUtil.NullOrEmpty(co.getGzDealerCode()) && dealerCode.equals(co.getGzDealerCode())){
					map.put("STATUS", "1");
				}else{
					map.put("STATUS", "0");
				}
			}
		}
		PageHelper.startPage(Integer.parseInt(pa.get("pageNo")),Integer.parseInt(pa.get("pageSize")));

        PageInfo<Map<String, Object>> page = new PageInfo<Map<String, Object>>(result);
        logger.info("page为————" + page);
		Map<String, Object> m = new HashMap<>();
		m.put("total", page.getTotal());
		m.put("rows", page.getList());
		m.put("resultCode", 1);
		return m;
	}

	/**
	 * 保存关注销售店
	 * 
	 * @author Administrator
	 * @date 2017年11月15日
	 * @return
	 */
	public Map<String, Object> upGzDealerCode(String dealerCode,Integer userId) {
		if(CheckUtil.NullOrEmpty(userId)){
			throw new ServiceBizException(ExceptionMessage.PARAM_NOT_ENOUGH);
		}
		TmCarOwner co = new TmCarOwner();
		co.setUserId(userId);
		co.setGzDealerCode(dealerCode);
		tmCarOwnerMapper.updateByPrimaryKeySelective(co);
		Map<String, Object> m = new HashMap<>();
		m.put("resultCode", 1);
		return m;
	}

	/**
	 * 查询城市列表
	 * 
	 * @author Administrator
	 * @date 2017年11月16日
	 * @return
	 */
	public List<Map<String, Object>> getCity() {
		List<Map<String, Object>> result = new ArrayList<>();
		List<MaintainDealerDto> temp = maintainServiceInterface.getCity(city);
		for (MaintainDealerDto maintainDto : temp) {
			Map<String, Object> m = new HashMap<>();
			m.put("REGION_CODE", maintainDto.getRegionCode());
			m.put("CITY", maintainDto.getRegionName());
			m.put("PROVINCE", "");
			result.add(m);
		}
		return result;
	}

	/**
	 * 查询销售顾问列表
	 * 
	 * @author Administrator
	 * @date 2017年11月17日
	 * @return
	 */
	public List<Map<String, Object>> getCounselorData(String dealerCode, String positionId) {
		List<Map<String, Object>> result = new ArrayList<>();
		String positionType = "";
		switch (positionId) {
		case "1":
			positionType = "601";
			break;
		case "2":
			positionType = "602";
			break;
		}
		List<CounselorDto> temp = customerServiceInterface.getCounselorData(dealerCode, positionType);
		for (CounselorDto counselorDto : temp) {
			Map<String, Object> m = new HashMap<>();
			m.put("dealerCode", (dealerCode == null) ? "" : dealerCode);
			m.put("SA_CODE", (counselorDto.getUserId() == null) ? "" : counselorDto.getUserId());
			m.put("SA_NAME", (counselorDto.getUserName() == null) ? "" : counselorDto.getUserName());
			m.put("employType", (positionId == null) ? "" : positionId);
			m.put("SA_PHONE", (counselorDto.getPhone() == null) ? "" : counselorDto.getPhone());
			result.add(m);
		}
		return result;
	}

	/**
	 * 查询养修预约车辆信息
	 * 
	 * @author Administrator
	 * @date 2017年11月17日
	 * @return
	 */
	public List<AppMaintainDto> getMaintainSel(String userId) {
		List<MaintainDto> result = maintainServiceInterface.getMaintainSel(userId);
		List<AppMaintainDto> re = new ArrayList<>();
		if (!CheckUtil.NullOrEmpty(result) && !result.isEmpty()) {
			for (MaintainDto MaintainDto : result) {
				AppMaintainDto appMa = new AppMaintainDto();
				MapConverUtil.ObjectToAppObject(MaintainDto, appMa);
				re.add(appMa);
			}
		}
		return re;
	}

	/**
	 * 获取工位空闲时间
	 * 
	 * @author Administrator
	 * @date 2017年11月20日
	 * @return
	 */
	public List<Map<String, Object>> getMrFreeTime(String dealerId) {
		List<Map<String, Object>> result = new ArrayList<>();
		List<String> temp = maintainServiceInterface.getMrFreeTime(dealerId);
		for (String s : temp) {
			Map<String, Object> m = new HashMap<>();
			m.put("timeInfo", s);
			m.put("freeFlag", 1);
			m.put("bookingNum", 999);
			result.add(m);
		}
		return result;
	}

	/**
	 * 选择预约类型
	 * 
	 * @author Administrator
	 * @date 2017年11月20日
	 * @return
	 */
	public List<Map<String, Object>> getMaintainType() {
		List<Map<String, Object>> type = new ArrayList<>();
		type = tmDealerMapper.getMaintainType();
		return type;
	}

	/**
	 * 保存预约信息
	 * 
	 * @author Administrator
	 * @date 2017年11月21日
	 * @return
	 */
	public Map<String, Object> saveMaintain(Map<String, Object> param) {
		logger.info("保存养修预约。。。。");
		Date applyDate = DateUtil.dateFormat(param.get("selectDate") + " " + param.get("selectTime") + ":00",
				"yyyy-MM-dd HH:mm:ss");
		MaintainDto maintainDto = new MaintainDto();
		maintainDto.setDealerCode((param.get("dealerId") == null) ? "" : param.get("dealerId").toString());
		maintainDto.setVin((param.get("vin") == null) ? "" : param.get("vin").toString());
		maintainDto.setReseApplStartTime(applyDate);
		maintainDto.setPhone((param.get("custTel") == null) ? "" : param.get("custTel").toString());
		maintainDto.setSalesConsultantId(param.get("saCode") == null? 0 : "".equals(param.get("saCode").toString())?0:Long.parseLong(param.get("saCode").toString()));
		maintainDto.setAppointType((param.get("appointType") == null) ? "" : param.get("appointType").toString());
		maintainDto.setSourceType(new Long(AppConstant.SOURCE_TYPE_10011002));
		maintainDto.setUserId((param.get("userId") == null) ? "" : param.get("userId").toString());
		maintainDto.setMaintainName((param.get("bookingName") == null) ? "" : param.get("bookingName").toString());
		maintainDto.setMileage((param.get("maintainKM") == null) ? "" : param.get("maintainKM").toString());
		maintainDto.setRemarks((param.get("remarks") == null) ? "" : param.get("remarks").toString());
		Map<String, Object> resultMap = maintainServiceInterface.saveMaintain(maintainDto);
		if (resultMap == null) {
			throw new ServiceBizException(ExceptionMessage.APP_SYSTEM_BUSYING);
		}
		if ("0".equals(resultMap.get("errorCode").toString())) {
			throw new ServiceBizException(resultMap.get("errorMsg").toString());
		}
		Map<String, Object> result = new HashMap<>();
		if ("1".equals(resultMap.get("errorCode").toString())) {
			String oddNumber = resultMap.get("data").toString();
			result = tmDealerMapper.getOddNumber(oddNumber);
		}
		return result;
	}

	/**
	 * 养修预约列表查询
	 * 
	 * @author Administrator
	 * @date 2017年11月22日
	 * @return
	 */
	public List<AppMaintainDto> getMaintainData(String userId) {
		List<AppMaintainDto> result = new ArrayList<>();
		List<MaintainDto> temp = maintainServiceInterface.getMaintainData(userId);
		for (MaintainDto m : temp) {
			AppMaintainDto appMaintainDto = new AppMaintainDto();
			MapConverUtil.ObjectToAppObject(m, appMaintainDto);
			result.add(appMaintainDto);
		}
		return result;
	}

	/**
	 * 查询预约详情
	 * 
	 * @author Administrator
	 * @date 2017年11月23日
	 * @return
	 */
	public List<AppMaintainDto> getMaintainDataById(String resnId) {
		List<AppMaintainDto> result = new ArrayList<>();
		List<MaintainDto> temp = maintainServiceInterface.getMaintainDataById(resnId);
		for (MaintainDto maintainDto : temp) {
			AppMaintainDto appMaintainDto = new AppMaintainDto();
			MapConverUtil.ObjectToAppObject(maintainDto, appMaintainDto);
			String applyStatus = (maintainDto.getApplyStatus() == null) ? ""
					: String.valueOf(maintainDto.getApplyStatus());
			switch (applyStatus) {
			case "10011001":
				applyStatus = "待确认";
				break;
			case "10011002":
				applyStatus = "已确认";
				break;
			case "10011005":
				applyStatus = "已取消";
				break;
			case "10011006":
				applyStatus = "已到店";
				break;
			}
			appMaintainDto.setApplyStatus(applyStatus);
			result.add(appMaintainDto);

		}
		return result;
	}

	/**
	 * 取消订单
	 * 
	 * @author Administrator
	 * @date 2017年11月23日
	 * @return
	 */
	public Map<String, Object> cancelAppoint(String appointCode) {
		MaintainFrecordDto maintainFrecordDto = new MaintainFrecordDto();
		maintainFrecordDto.setApplyStatus(cancle);
		maintainFrecordDto.setResnId(Long.valueOf(appointCode));
		Map<String, Object> result = maintainServiceInterface.cancelAppoint(maintainFrecordDto);
		return result;
	}

}
